<template>
  <div>
    <div v-if="editOpen" style="width: 100%;">
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                   @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data" :columns="columns">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #company="{ row }">
              <t-tree-select :status="row.companyStatus" @change="(val,content)=>{row.companyId=content.node.data.id;if(row.company!==''){row.companyStatus = 'default'}}" v-if="row.isInnerCompany==='1'" style="width:390px" clearable filterable
                             :treeProps="{keys: {value: 'label'}}" v-model="row.company" :data="deptMenuOptions"
                             placeholder="选择单位">
                <div slot="tips" v-if="row.companyStatus==='error'">不能为空</div>
                <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="row.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{row.company='';row.companyId=null;row.companyStatus='default'}"
                  ></t-switch>
                </template>
              </t-tree-select>
              <t-select
                v-else
                v-model="row.company"
                creatable
                filterable
                placeholder="请输入"
                :status="row.companyStatus"
                @change="(val,content)=>{row.companyId = content.option?.id;if(row.company!==''){row.companyStatus = 'default'}}"
                :loading="companyLoading"
                @search="remoteCompanyMethod"
                :options="companyOptions"
                @create="createCompanyOptions"
                style="width: 390px;display: inline-block"
              >
                <div slot="tips" v-if="row.companyStatus==='error'">不能为空</div>
                <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="row.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{row.company='';row.companyId=null;row.companyStatus='default'}"
                  ></t-switch>
                </template>
              </t-select>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button @click="addData">新增
            </t-button>
            <t-button @click="upData">上移</t-button>
            <t-button @click="downData">下移</t-button>
            <t-button @click="delData">删除</t-button>
          </div>
        </t-col>
      </t-row>
    </div>
    <div v-else style="width: 100%;">
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-table :loading="dataLoading" size="small" rowKey="id" :data="data" :columns="columns2">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #company="{ row,rowIndex }">
              <t-link @click="dialog.objId=row.companyId;dialog.header=row.company;dialog.open_detail=true" hover="color" theme="primary">
                {{row.company}}
              </t-link>
            </template>
            <template #isInnerCompany="{ row }">
              {{row.isInnerCompany?'是':'否'}}
            </template>
          </t-table>
        </t-col>
      </t-row>
    </div>
    <unit-all-detail :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_detail" v-if="dialog.open_detail"></unit-all-detail>
  </div>
</template>

<script>
import unitAllDetail from "@/pages/common/system/components/unit-all-detail.vue";

export default {
  name: "copyright-company",
  components: {
    unitAllDetail
  },
  props: {
    value: Array,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      dialog:{
        objId: null,
        header: '',
        open_detail: false,
      },
      companyLoading: false,
      companyOptions: [],
      dataLoading: false,
      deptMenuOptions: [],
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否内部单位",
        //   width: 120,
        // },
        {
          colKey: "company",
          title: "单位名称",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "isInnerCompany",
          title: "是否内部单位",
          align: "center",
        },
        {
          colKey: "company",
          title: "单位名称",
          align: "center",
        },
      ],
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getCompanyList(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
  },
  created() {
    this.getDeptTreeSelect()
  },
  methods: {
    createCompanyOptions(value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod(search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName: search}).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (!val.company) {
          this.$set(this.data[index], 'companyStatus', 'error')
          this.$message.error(`专利权人：第${index + 1}条"单位名称"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'companyStatus', 'default')
        return true;
      });
      return isValidate;
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getCompanyList() {
      if (this.objId) {
        this.dataLoading = true;
        this.$api.cgzh.copyright.companyListGet(this.objId).then(response => {
          this.data = response.data;
          this.dataLoading = false;
        }).catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });
      }
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    addData() {
      this.data.push({
        softId: this.objId,
        company: '',
        id: Date.parse(new Date()),
        companyId: null,
        isInnerCompany: '1'
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1);
      this.selectedRowKeys = [];
    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
